import { useSelector, useDispatch } from 'react-redux'
import classNames from 'classnames'
import { todoDel, updateAllTodo, updateTodoStatus } from '../store/actions/todo'
import { useState, useRef, useEffect } from 'react'

export default function TodoMain() {
  const inputRef = useRef()
  const dispatch = useDispatch()
  const { todo } = useSelector((state) => state)
  const [editId, setEditId] = useState('')
  const handleDelete = (id) => dispatch(todoDel(id))
  const handleUpdateTodoStatus = (id) => dispatch(updateTodoStatus(id))
  const handleChangeAll = (done) => dispatch(updateAllTodo(done))

  // 双击显示编辑框
  const handleDblClick = (id) => {
    setEditId(id)
    // inputRef.current => DOM
  }
  // !先确定全选的状态
  const isCheckedAll = todo.every((item) => item.done)

  useEffect(() => {
    if (editId === '') return
    inputRef.current.focus()
  }, [editId])

  return (
    <section className='main'>
      <input
        id='toggle-all'
        className='toggle-all'
        type='checkbox'
        checked={isCheckedAll}
        onChange={() => handleChangeAll(!isCheckedAll)}
      />
      <label htmlFor='toggle-all'>Mark all as complete</label>
      <ul className='todo-list'>
        {todo.map((item) => (
          <li
            key={item.id}
            className={classNames({
              completed: item.done,
              editing: editId === item.id,
            })}
          >
            <div className='view'>
              <input
                className='toggle'
                type='checkbox'
                checked={item.done}
                onChange={() => handleUpdateTodoStatus(item.id)}
              />
              <label onDoubleClick={() => handleDblClick(item.id)}>
                {item.name}
              </label>
              <button
                className='destroy'
                onClick={() => handleDelete(item.id)}
              ></button>
            </div>
            {/* 做编辑用的 */}
            <input
              className='edit'
              value='Create a TodoMVC template'
              onChange={() => {}}
              ref={inputRef}
            />
          </li>
        ))}
      </ul>
    </section>
  )
}
